/*
	Class: DocElemStyles
	
		This class handles the <style /> tag.
*/
package com.frontalcode 
{
	/**
	 * The DocElemInclude class handles the <style /> tag.
	 */
    public class DocElemStyles extends DocumentElement
    {
		/*
			Variable: stylesheetOrder
			
				We keep track of the order of the associated styles in relation to
				other stylesheets. This is to support the ordering of selectors
				when applying more than one at a time to an element. (Styles
				declared later have precedence over styles declared earlier.)
		*/
		/**
		 * @private
		 */
		internal var stylesheetOrder : Number;
		
		/**
		 * @private
		 */
		internal var stylesheetSelectors : Array = [ ];
		
		/**
		 * Creates a new DocElemStyles instance.
		 * 
		 * @param document	The document this element belongs to.
		 * @param parent	The element's parent in the document tree.
		 * @param node		The XML node this element is associated with.
		 * @param options	Options affecting the behavior of this instance.
		 * 					(This object does not have built-in support for any
		 * 					options.)
		 */
		public function DocElemStyles ( document : Document, parent : DocumentElement, node : XML, options : Object = null )
		{
			super ( document, parent, node, options );
			
			processesOwnContent = true;
			
			stylesheetOrder = StylesheetParser.getInstance ( ).parse ( node.text ( ).toString ( ), this );
		}
		
		/**
		 * @private
		 */
		internal function addStyleRuleSet ( selectors : Array, declarations : Array ) : void
		{
			var attributes : Attributes = new Attributes ( document.stylesManager );
			var actions : Object = { };

			for each ( var declaration : Object in declarations )
			{
				if ( declaration.attribute != null )
				{
					attributes.setAttribute ( declaration.attribute, declaration.value, declaration.attributeNamespace );
				}
				else if ( declaration.action != null )
				{
					actions [ declaration.action ] = declaration.value;
				}
				else
				{
					attributes.styles.setStyle ( declaration.style, declaration.value, true );
				}
			}
			
			for ( var i : uint = 0; i < selectors.length; i++ )
			{
				stylesheetSelectors.push ( new StylesheetSelector ( document, selectors [ i ], attributes, actions ) );
			}
		}
		
		/**
		 * @private
		 */
		override public function destroy ( ) : void
		{
			super.destroy ( );
			
			for each ( var stylesheetSelector : StylesheetSelector in stylesheetSelectors )
			{
				document.stylesManager.unregisterStylesheetSelector ( stylesheetSelector );
			}
		}
	}
}
